package com.lagou.zuoye.servlet;

import com.lagou.zuoye.bean.Student;
import com.lagou.zuoye.dao.StudentDao;
import com.lagou.zuoye.dao.StudentDaoImp;
import com.lagou.zuoye.factory.StudentDaoFactory;
import com.lagou.zuoye.service.StudentService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "AddServlet",urlPatterns = "/add")
public class AddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String userName = request.getParameter("name");
        String sex = request.getParameter("sex");
        String birthday = request.getParameter("birthday");
        String email = request.getParameter("email");
        String notes = request.getParameter("notes");

        System.out.println(sex);

        //2.创建StudentService对象来获取StudentDaoImp的对象
        StudentDao studentDao = StudentDaoFactory.getStudentDao();
        Student student = new Student(null, userName, sex, birthday, email, notes);
        int i = studentDao.addStudent(student);
        System.out.println(i);
        if(i==-1){
            System.out.println("添加学员失败");
            request.setAttribute("error","添加失败，学员信息不完整");
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("list.jsp");
            requestDispatcher.forward(request,response);
        }else{
            System.out.println("添加学员成功");
            request.getSession().setAttribute("student",student);
            response.sendRedirect("add.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
